<?php

class banners extends Module {
	
	private
		$aPagesAssoc     = null,
		$aPositionsAssoc = null;
	
	public function __construct () {
		parent::__construct (__CLASS__);		
	}
	
	public function __default () {
		throw new NotFound;
	}
	
	public function get ($pageType, $position) {
		$response = new ModuleResponse;
		
		$oTypeBanner = TypesController::getInstance()->getTypeByName('banner');
		
		$aPagesTypes = $this->getPagesAssoc();
		if (!isset($aPagesTypes[$pageType])) {
			return $response;
		}
		$pageTypeId = $aPagesTypes[$pageType];

		$aPosisions = $this->getPositionsAssoc();
		if (!isset($aPosisions[$position])) {
			return $response;
		}
		$positionId = $aPosisions[$position];
		
		$sel = new Selection;
		$sel->addType($oTypeBanner);
		$sel->addFilter('pages',$pageTypeId);
		$sel->addFilter('position',$positionId);
		$sel->addFilter('active', '1');
		$sel->addFiltersGroup(array(
			array ('date_start', time(), '<'),
			array ('date_start', '', '=')), 'OR');
		$sel->addFiltersGroup(array(
			array ('date_end', time(), '>'),
			array ('date_end', '', '=')), 'OR');		
						
		$sel->setOrder('weight');
		
		$aObjects = ObjectsController::getInstance()->getObjectsList($sel->getList());
		
		foreach ($aObjects as $object) {
			$object->disableHTMLFilter('content', false);
			$response->addObject($object);
		}
		
		return $response;
	}
	
	private function getPagesAssoc () {
		if ($this->aPagesAssoc === null) {
			$this->aPagesAssoc = array ();
			
			$oTypePage = TypesController::getInstance()->getTypeByName('banners_page_type');
			
			$sel = new Selection;
			$sel->addType($oTypePage);
			$sel->addSelectedProperty('alias');
			
			$res = $sel->getList();
			
			foreach ($res as $row) {
				$this->aPagesAssoc[$row['alias']] = $row[0];
			}
		}
		
		return $this->aPagesAssoc;
	}
	
	private function getPositionsAssoc () {
		if ($this->aPositionsAssoc === null) {
			$this->aPositionsAssoc = array ();
			
			$oTypePosition = TypesController::getInstance()->getTypeByName('banner_position');
			
			$sel = new Selection;
			$sel->addType($oTypePosition);
			$sel->addSelectedProperty('alias');
			
			$res = $sel->getList();
			
			foreach ($res as $row) {
				$this->aPositionsAssoc[$row['alias']] = $row[0];
			}
		}
		
		return $this->aPositionsAssoc;
	}
	
}